import React, { useState } from 'react'
import * as Radash from 'radash'

type Role = 'admin' | 'system' | 'user'

interface User {
    id: number
    name: string
    role: Role
}

const USERS: User[] = [
    {
        id: 1,
        name: 'admin',
        role: 'admin'
    },
    {
        id: 2,
        name: Radash.uid(4),
        role: 'system'
    },
    {
        id: 3,
        name: Radash.uid(4),
        role: 'user'
    },
    {
        id: 4,
        name: Radash.uid(4),
        role: 'user'
    },
    {
        id: 5,
        name: Radash.uid(4),
        role: 'system'
    }
]

interface ItemProps {
    role: Role,
    user: User[]
}

export function Item ({ role, user }: ItemProps) {

    return (
        <li>
            <h1 className={'text-2xl border-b-2 mb-5'}>{ role }</h1>
            <ul className={'flex flex-col gap-2'}>
                {
                    user.map((user) => (
                        <li key={ user.id } className={''}>
                            { user.name }
                        </li>
                    ))
                }
            </ul>
        </li>
    )
}

export function Group () {

    const [ users, setUsers ] = useState(USERS)

    const groups: Record<Role, User[]> = Object.groupBy(users, (user: User) => user.role) as Record<Role, User[]>

    const add = () => {
        setUsers([
            ...users,
            {
                id: Math.round(1),
                name: Radash.uid(4),
                role: 'user'
            }
        ])
    }
    return (
        <div className={ 'p-20' }>

            <button className={'p-5 bg-rose-500 text-white mb-10'}
                    onClick={ add }>
                add
            </button>
            <ul className={ 'flex flex-col gap-5' }>
                {
                    (Object.keys(groups) as Role[]).map((role) => (
                        <Item key={ role } role={ role } user={ groups[role] }/>
                    ))
                }
            </ul>
        </div>
    )
}

